#!/usr/bin/env python
# Create: 2019/1/17
__author__ = '749B'

import importlib
import os
import requests


def check_and_create_folder(path):
    if not os.path.exists(path):
        print("创建文件夹:", path)
        os.makedirs(path)


def get(course, part, filename, base_url):
    base_dir = os.path.dirname(__file__)
    folder = os.path.join(base_dir, 'download', course, part or '')
    check_and_create_folder(folder)
    fullname = os.path.join(folder, filename + '.ts')

    print("下载到文件:", filename)
    with open(fullname, 'wb') as file:
        n = 0
        while True:
            url = "%s%s.ts" % (base_url, n)
            print("\r下载地址:", url, end="", flush=True)
            r = requests.get(url)
            if r:
                data = r.content
                file.write(data)
                n += 1
            else:
                break
        print("\n关闭文件")


def main(module_name):
    module = importlib.import_module("data.%s" % module_name)
    urls = iter(module.URLS)
    course = module.COURSE
    for url_info in urls:
        get(course, *url_info)


def choice_course(courses):
    for i, course in enumerate(courses):
        print("%2d %s %s" % (i, course[0], course[1]))
    course_num = input("选择课程的序号：")
    if not course_num.isdigit():
        exit("无效的数字")
    course_index = int(course_num)
    if course_index >= len(courses):
        exit("不存在的序号")
    ok = input('选择课程"%s"，确认下载：' % courses[course_index][0])
    if ok.lower() in ["y", "yes"]:
        return courses[course_index][1]
    else:
        exit("放弃操作")


if __name__ == '__main__':
    data_file_list = [
        ("机器学习", "Machine_Learning"),
        ("深度学习和神经网络", "DeepLearningAndNeuralNetwork"),
        ("Python编程入门", "IntroducingPython"),
        ("机器学习理解与实战", "MachineLearningInAction"),
        ("深度学习的发展与应用", "DeepLearningDevelopmentAndApplication"),
        ("实用数据挖掘与人工智能一月特训班", "DataMiningAndAI_MonthTrain"),
        ("高等数学—正态分布", "NormalDistribution")
    ]
    data_file = choice_course(data_file_list)
    main(data_file)
    print("完成")

